#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("cf server");

    //创建实例
    serverTcp = new QTcpServer(this);

    //链接信号槽
    connect(serverTcp,&QTcpServer::newConnection,this,&Widget::proessConnection);

    //最后绑定并监听
    bool ret = serverTcp->listen(QHostAddress::Any,8080);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器启动失败",serverTcp->errorString());
        exit(1);
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::proessConnection()
{
    //拿到socket
    QTcpSocket* clientSocket = serverTcp->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + ":" +
            QString::number(clientSocket->peerPort()) + "] 客户端上线.";
    ui->listWidget->addItem(log);


    //获取链接，通过信号槽处理请求
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        //读取请求数据
        QString request = clientSocket->readAll();
        //处理数据响应
        const QString& response = process(request);
        //把响应回复给客户端
        clientSocket->write(response.toUtf8());

        //记录日志
        QString logNormal = "[" + clientSocket->peerAddress().toString() + ":" +
                QString::number(clientSocket->peerPort()) + "] req: " + request
                + ", resp: " + response;
        ui->listWidget->addItem(logNormal);
        qDebug() << logNormal;
    });

    //客户端断开链接，任务槽处理
    connect(clientSocket,&QTcpSocket::disconnected,this,[=](){
        QString logNormal = "[" + clientSocket->peerAddress().toString() + ":" +
                QString::number(clientSocket->peerPort()) + "] 客户端下线.";
        ui->listWidget->addItem(logNormal);

        clientSocket->deleteLater();

        //delete clientSocket;

    });

}

//业务处理函数
QString Widget::process(const QString &request)
{
    return request;
}

